#include "audiocapture.h"
#include <QDebug>
#include <QDir>
#include <QStandardPaths>
#include <QCoreApplication>

AudioCapture::AudioCapture(QObject *parent)
    : QObject(parent)
    , m_audioSource(nullptr)
    , m_audioIODevice(nullptr)
    , m_isCapturing(false)
    , m_useOutputDevice(false)
    , m_dataSizePosition(0)
    , m_fileSizePosition(0)
    , m_dataStartPosition(0)
    , m_transmitter(nullptr)
    , m_transmissionEnabled(false)
    , m_transmissionHost("localhost")
    , m_transmissionPort(8766)
{
    setupAudioFormat();
    
    // 初始化音频传输器
    m_transmitter = new AudioTransmitter(this);
    
    // 连接传输器信号
    connect(m_transmitter, &AudioTransmitter::transmissionStatusChanged,
            this, &AudioCapture::onTransmissionStatusChanged);
    connect(m_transmitter, &AudioTransmitter::error,
            this, &AudioCapture::onTransmissionError);
    connect(m_transmitter, &AudioTransmitter::dataSent,
            this, &AudioCapture::onTransmissionDataSent);
    connect(m_transmitter, &AudioTransmitter::connectionEstablished,
            this, &AudioCapture::onTransmissionConnectionEstablished);
    connect(m_transmitter, &AudioTransmitter::connectionLost,
            this, &AudioCapture::onTransmissionConnectionLost);
    
    // 检测并显示可用的音频设备信息
    QList<QAudioDevice> inputDevices = QMediaDevices::audioInputs();
    QList<QAudioDevice> outputDevices = QMediaDevices::audioOutputs();
    QAudioDevice defaultInput = QMediaDevices::defaultAudioInput();
    QAudioDevice defaultOutput = QMediaDevices::defaultAudioOutput();
    
    qDebug() << "=== 音频设备检测 ===";
    qDebug() << "检测到" << inputDevices.size() << "个音频输入设备:";
    
    for (const QAudioDevice &device : inputDevices) {
        QString deviceInfo = QString("  - %1 (ID: %2)")
            .arg(device.description().isEmpty() ? device.id() : device.description())
            .arg(device.id());
        
        if (device == defaultInput) {
            deviceInfo += " [默认输入]";
        }
        
        qDebug() << deviceInfo;
    }
    
    qDebug() << "检测到" << outputDevices.size() << "个音频输出设备:";
    
    for (const QAudioDevice &device : outputDevices) {
        QString deviceInfo = QString("  - %1 (ID: %2)")
            .arg(device.description().isEmpty() ? device.id() : device.description())
            .arg(device.id());
        
        if (device == defaultOutput) {
            deviceInfo += " [默认输出]";
        }
        
        qDebug() << deviceInfo;
    }
    
    if (defaultInput.id() != QString()) {
        qDebug() << "系统默认音频输入设备:" << defaultInput.description();
    } else {
        qWarning() << "警告: 未找到系统默认音频输入设备";
    }
    
    if (defaultOutput.id() != QString()) {
        qDebug() << "系统默认音频输出设备:" << defaultOutput.description();
    } else {
        qWarning() << "警告: 未找到系统默认音频输出设备";
    }
    qDebug() << "=====================";
}

AudioCapture::~AudioCapture()
{
    stopCapture();
}

void AudioCapture::setupAudioFormat()
{
    // 使用更兼容的音频格式
    m_audioFormat.setSampleRate(48000);  // 使用48kHz，更兼容
    m_audioFormat.setChannelCount(2);    // 立体声
    m_audioFormat.setSampleFormat(QAudioFormat::Int16);
}

bool AudioCapture::startCapture(const QString &deviceId, const QString &outputFilePath)
{
    if (m_isCapturing) {
        qWarning() << "音频捕获已在运行中";
        return false;
    }
    
    // 检查输出文件路径
    QFileInfo fileInfo(outputFilePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            emit captureError("无法创建输出目录");
            return false;
        }
    }
    
    // 初始化音频捕获
    if (!initializeAudioCapture(deviceId)) {
        return false;
    }
    
    // 打开输出文件
    m_outputFilePath = outputFilePath;
    m_outputFile.setFileName(outputFilePath);
    
    if (!m_outputFile.open(QIODevice::WriteOnly)) {
        emit captureError("无法打开输出文件进行写入");
        return false;
    }
    
    // 写入WAV文件头
    writeWavHeader();
    
    // 启动音频捕获
    if (m_useOutputDevice) {
        // 使用音频输出设备捕获（需要系统支持）
        if (!setupOutputCapture()) {
            emit captureError("设置音频输出捕获失败");
            m_outputFile.close();
            return false;
        }
    } else {
        // 使用传统音频输入捕获
        m_audioIODevice = m_audioSource->start();
        if (!m_audioIODevice) {
            emit captureError("无法启动音频输入设备");
            m_outputFile.close();
            return false;
        }
        
        // 连接信号
        connect(m_audioIODevice, &QIODevice::readyRead, this, &AudioCapture::onAudioDataReady);
    }
    
    m_isCapturing = true;
    emit captureStatusChanged(true);
    
    qDebug() << "音频捕获已启动，输出文件:" << outputFilePath;
    if (m_useOutputDevice) {
        qDebug() << "使用音频输出设备捕获模式";
    } else {
        qDebug() << "使用音频输入设备捕获模式";
    }
    return true;
}

void AudioCapture::stopCapture()
{
    if (!m_isCapturing) {
        return;
    }
    
    qDebug() << "停止音频捕获...";
    
    // 停止音频输入
    if (m_audioSource) {
        m_audioSource->stop();
        disconnect(m_audioSource, nullptr, this, nullptr);
    }
    
    if (m_audioIODevice) {
        disconnect(m_audioIODevice, nullptr, this, nullptr);
        m_audioIODevice = nullptr;
    }
    
    // 完成WAV文件
    if (m_outputFile.isOpen()) {
        finalizeWavFile();
        m_outputFile.close();
    }
    
    m_isCapturing = false;
    emit captureStatusChanged(false);
    
    qDebug() << "音频捕获已停止";
}

bool AudioCapture::initializeAudioCapture(const QString &deviceId)
{
    // 如果deviceId为空或者是"default"，则使用系统默认设备
    if (deviceId.isEmpty() || deviceId == "default") {
        // 优先尝试使用默认音频输出设备
        m_audioDevice = QMediaDevices::defaultAudioOutput();
        if (m_audioDevice.id() != QString()) {
            qDebug() << "使用系统默认音频输出设备:" << m_audioDevice.description();
            m_useOutputDevice = true;
        } else {
            // 如果没有输出设备，回退到输入设备
            m_audioDevice = QMediaDevices::defaultAudioInput();
            if (m_audioDevice.id() == QString()) {
                emit captureError("未找到有效的音频设备");
                return false;
            }
            qDebug() << "使用系统默认音频输入设备:" << m_audioDevice.description();
            m_useOutputDevice = false;
        }
    } else {
        // 查找指定的音频设备
        QList<QAudioDevice> outputDevices = QMediaDevices::audioOutputs();
        QList<QAudioDevice> inputDevices = QMediaDevices::audioInputs();
        bool deviceFound = false;
        
        // 首先查找输出设备
        for (const QAudioDevice &device : outputDevices) {
            if (device.id() == deviceId || device.description() == deviceId) {
                m_audioDevice = device;
                deviceFound = true;
                m_useOutputDevice = true;
                break;
            }
        }
        
        // 如果没有找到输出设备，查找输入设备
        if (!deviceFound) {
            for (const QAudioDevice &device : inputDevices) {
                if (device.id() == deviceId || device.description() == deviceId) {
                    m_audioDevice = device;
                    deviceFound = true;
                    m_useOutputDevice = false;
                    break;
                }
            }
        }
        
        if (!deviceFound) {
            qWarning() << "未找到指定设备:" << deviceId << "，使用系统默认设备";
            m_audioDevice = QMediaDevices::defaultAudioOutput();
            if (m_audioDevice.id() != QString()) {
                m_useOutputDevice = true;
            } else {
                m_audioDevice = QMediaDevices::defaultAudioInput();
                m_useOutputDevice = false;
            }
            
            if (m_audioDevice.id() == QString()) {
                emit captureError("未找到有效的音频设备");
                return false;
            }
        }
    }
    
    // 检查设备是否支持我们的音频格式
    if (!m_audioDevice.isFormatSupported(m_audioFormat)) {
        qWarning() << "设备不支持指定格式，尝试协商最佳格式...";
        
        // 尝试找到支持的格式
        QAudioFormat supportedFormat = m_audioDevice.preferredFormat();
        qDebug() << "设备首选格式:"
                   << "采样率:" << supportedFormat.sampleRate()
                   << "通道数:" << supportedFormat.channelCount()
                   << "采样格式:" << supportedFormat.sampleFormat();
        
        // 尝试使用设备首选格式
        if (supportedFormat.sampleRate() > 0 && supportedFormat.channelCount() > 0) {
            m_audioFormat = supportedFormat;
        } else {
            // 如果设备首选格式无效，尝试常用格式
            // 检查支持的采样格式
            QList<QAudioFormat::SampleFormat> supportedFormats = m_audioDevice.supportedSampleFormats();
            
            if (!supportedFormats.isEmpty()) {
                // 尝试常用的采样率和通道数组合
                QList<int> commonRates = {48000, 44100, 16000, 8000};
                QList<int> commonChannels = {2, 1};
                
                bool formatFound = false;
                for (int rate : commonRates) {
                    for (int channels : commonChannels) {
                        QAudioFormat testFormat;
                        testFormat.setSampleRate(rate);
                        testFormat.setChannelCount(channels);
                        testFormat.setSampleFormat(supportedFormats.first());
                        
                        if (m_audioDevice.isFormatSupported(testFormat)) {
                            m_audioFormat = testFormat;
                            formatFound = true;
                            qDebug() << "找到支持的格式组合:"
                                       << "采样率:" << m_audioFormat.sampleRate()
                                       << "通道数:" << m_audioFormat.channelCount()
                                       << "采样格式:" << m_audioFormat.sampleFormat();
                            break;
                        }
                    }
                    if (formatFound) break;
                }
                
                if (!formatFound) {
                    // 最后的回退：使用最基本的格式
                    m_audioFormat.setSampleRate(16000);
                    m_audioFormat.setChannelCount(1);
                    m_audioFormat.setSampleFormat(QAudioFormat::Int16);
                    qWarning() << "使用回退格式: 16kHz, 单声道, 16位";
                }
            } else {
                // 最后的回退：使用最基本的格式
                m_audioFormat.setSampleRate(16000);
                m_audioFormat.setChannelCount(1);
                m_audioFormat.setSampleFormat(QAudioFormat::Int16);
                qWarning() << "使用回退格式: 16kHz, 单声道, 16位";
            }
        }
    }
    
    qDebug() << "最终使用音频格式:"
               << "采样率:" << m_audioFormat.sampleRate()
               << "通道数:" << m_audioFormat.channelCount()
               << "采样格式:" << m_audioFormat.sampleFormat();
    
    // 创建音频源对象
    m_audioSource = new QAudioSource(m_audioDevice, m_audioFormat, this);
    
    // 设置缓冲区大小
    m_audioSource->setBufferSize(4096); // 4KB缓冲区
    
    connect(m_audioSource, &QAudioSource::stateChanged, this, &AudioCapture::onAudioSourceStateChanged);
    
    return true;
}

bool AudioCapture::setupOutputCapture()
{
    // 对于音频输出设备，我们需要使用特殊的捕获方法
    // 在Windows上，这通常需要WASAPI loopback模式或其他系统级支持
    
    qDebug() << "尝试设置音频输出捕获...";
    
    // 启动音频源
    m_audioIODevice = m_audioSource->start();
    if (!m_audioIODevice) {
        qWarning() << "无法启动音频输出捕获，回退到输入设备";
        
        // 回退到输入设备
        m_useOutputDevice = false;
        m_audioDevice = QMediaDevices::defaultAudioInput();
        if (m_audioDevice.id() == QString()) {
            qWarning() << "无法获取默认音频输入设备";
            return false;
        }
        
        // 重新创建音频源
        delete m_audioSource;
        m_audioSource = new QAudioSource(m_audioDevice, m_audioFormat, this);
        m_audioSource->setBufferSize(4096);
        connect(m_audioSource, &QAudioSource::stateChanged, this, &AudioCapture::onAudioSourceStateChanged);
        
        m_audioIODevice = m_audioSource->start();
        if (!m_audioIODevice) {
            qWarning() << "重新初始化音频输入设备失败";
            return false;
        }
        
        qDebug() << "已回退到音频输入设备:" << m_audioDevice.description();
    }
    
    // 连接数据读取信号
    connect(m_audioIODevice, &QIODevice::readyRead, this, &AudioCapture::onAudioDataReady);
    
    QString deviceType = m_useOutputDevice ? "音频输出设备" : "音频输入设备";
    qDebug() << deviceType << "捕获设置完成";
    return true;
}

void AudioCapture::writeWavHeader()
{
    QDataStream stream(&m_outputFile);
    stream.setByteOrder(QDataStream::LittleEndian);
    
    // RIFF头
    stream.writeRawData("RIFF", 4);
    m_fileSizePosition = m_outputFile.pos();
    stream << quint32(0); // 文件大小占位符
    stream.writeRawData("WAVE", 4);
    
    // fmt子块
    stream.writeRawData("fmt ", 4);
    stream << quint32(16); // fmt子块大小
    stream << quint16(1);  // 音频格式 (PCM)
    stream << quint16(m_audioFormat.channelCount());
    stream << quint32(m_audioFormat.sampleRate());
    stream << quint32(m_audioFormat.sampleRate() * m_audioFormat.channelCount() * m_audioFormat.bytesPerSample());
    stream << quint16(m_audioFormat.channelCount() * m_audioFormat.bytesPerSample());
    stream << quint16(m_audioFormat.bytesPerSample() * 8);
    
    // data子块
    stream.writeRawData("data", 4);
    m_dataSizePosition = m_outputFile.pos();
    stream << quint32(0); // 数据大小占位符
    
    m_dataStartPosition = m_outputFile.pos();
}

void AudioCapture::finalizeWavFile()
{
    if (!m_outputFile.isOpen()) {
        return;
    }
    
    qint64 dataEndPosition = m_outputFile.pos();
    qint64 dataSize = dataEndPosition - m_dataStartPosition;
    qint64 fileSize = dataEndPosition - 8;
    
    // 更新文件大小
    m_outputFile.seek(m_fileSizePosition);
    QDataStream stream(&m_outputFile);
    stream.setByteOrder(QDataStream::LittleEndian);
    stream << quint32(fileSize);
    
    // 更新数据大小
    m_outputFile.seek(m_dataSizePosition);
    stream << quint32(dataSize);
    
    qDebug() << "WAV文件已完成，数据大小:" << dataSize << "字节";
}

void AudioCapture::onAudioDataReady()
{
    if (!m_isCapturing || !m_audioIODevice) {
        return;
    }
    
    // 读取音频数据并写入文件
    QByteArray audioData = m_audioIODevice->readAll();
    if (!audioData.isEmpty()) {
        // 验证音频数据
        if (audioData.size() > 0 && audioData.size() < 1024 * 1024) { // 限制1MB
            m_outputFile.write(audioData);
            m_outputFile.flush();
            
            // 如果音频传输已启用，发送音频数据
            if (m_transmissionEnabled && m_transmitter) {
                m_transmitter->sendAudioData(audioData);
            }
        } else {
            qWarning() << "音频数据异常，大小:" << audioData.size() << "字节";
        }
    }
}

void AudioCapture::onAudioSourceStateChanged(QAudio::State state)
{
    qDebug() << "音频源状态改变:" << state;
    
    switch (state) {
    case QAudio::ActiveState:
        qDebug() << "音频源处于活动状态";
        break;
    case QAudio::SuspendedState:
        qDebug() << "音频源已暂停";
        break;
    case QAudio::StoppedState:
        qDebug() << "音频源已停止";
        if (m_isCapturing) {
            stopCapture();
        }
        break;
    case QAudio::IdleState:
        qDebug() << "音频源处于空闲状态";
        break;
    }
}

// 音频传输相关方法实现
bool AudioCapture::startTransmission(const QString &host, quint16 port)
{
    if (!m_transmitter) {
        qWarning() << "音频传输器未初始化";
        return false;
    }
    
    m_transmissionHost = host;
    m_transmissionPort = port;
    
    // 连接到服务器
    if (m_transmitter->connectToServer(host, port)) {
        m_transmissionEnabled = true;
        m_transmitter->setTransmissionEnabled(true);
        qDebug() << "音频传输已启动，连接到" << host << ":" << port;
        return true;
    } else {
        qWarning() << "音频传输启动失败";
        return false;
    }
}

void AudioCapture::stopTransmission()
{
    if (m_transmitter) {
        m_transmitter->setTransmissionEnabled(false);
        m_transmitter->disconnectFromServer();
        m_transmissionEnabled = false;
        qDebug() << "音频传输已停止";
    }
}

void AudioCapture::setTransmissionEnabled(bool enabled)
{
    if (m_transmissionEnabled == enabled) {
        return;
    }
    
    m_transmissionEnabled = enabled;
    
    if (m_transmitter) {
        m_transmitter->setTransmissionEnabled(enabled);
    }
    
    qDebug() << "音频传输" << (enabled ? "已启用" : "已禁用");
}

void AudioCapture::setTransmissionHost(const QString &host)
{
    m_transmissionHost = host;
    if (m_transmitter) {
        // 如果当前已连接，重新连接
        if (m_transmitter->isConnected()) {
            m_transmitter->disconnectFromServer();
            m_transmitter->connectToServer(host, m_transmissionPort);
        }
    }
    qDebug() << "传输主机设置为:" << host;
}

void AudioCapture::setTransmissionPort(quint16 port)
{
    m_transmissionPort = port;
    if (m_transmitter) {
        // 如果当前已连接，重新连接
        if (m_transmitter->isConnected()) {
            m_transmitter->disconnectFromServer();
            m_transmitter->connectToServer(m_transmissionHost, port);
        }
    }
    qDebug() << "传输端口设置为:" << port;
}

void AudioCapture::setTransmissionBufferSize(int size)
{
    if (m_transmitter) {
        m_transmitter->setBufferSize(size);
    }
}

void AudioCapture::setTransmissionInterval(int intervalMs)
{
    if (m_transmitter) {
        m_transmitter->setTransmissionInterval(intervalMs);
    }
}

void AudioCapture::setTransmissionCompression(bool enabled)
{
    if (m_transmitter) {
        m_transmitter->setCompressionEnabled(enabled);
    }
}

// 传输相关槽函数实现
void AudioCapture::onTransmissionStatusChanged(bool enabled)
{
    m_transmissionEnabled = enabled;
    emit transmissionStatusChanged(enabled);
    qDebug() << "传输状态改变:" << (enabled ? "已启用" : "已禁用");
}

void AudioCapture::onTransmissionError(const QString &error)
{
    emit transmissionError(error);
    qWarning() << "传输错误:" << error;
}

void AudioCapture::onTransmissionDataSent(qint64 bytesSent)
{
    emit transmissionDataSent(bytesSent);
    qDebug() << "传输数据已发送:" << bytesSent << "字节";
}

void AudioCapture::onTransmissionConnectionEstablished()
{
    emit transmissionConnectionEstablished();
    qDebug() << "传输连接已建立";
}

void AudioCapture::onTransmissionConnectionLost()
{
    emit transmissionConnectionLost();
    qDebug() << "传输连接已断开";
}


